<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <p>
        选择商品分类：
        <el-cascader
          v-model="selectedKeys"
          :options="cateList"
          :props="cascaderProps"
          @change="cateChange"
          expand-trigger="hover"
        ></el-cascader>
      </p>

      <!-- 属性配置区域 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" @click="showAddParam" :disabled="isBtnDisable">添加参数</el-button>
          <el-table :data="paramOrPropData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.newParamVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addNewTag(scope.row)"
                  @blur="addNewTag(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  class="el-icon-edit"
                  @click="showEditParam(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" @click="showAddParam" :disabled="isBtnDisable">添加属性</el-button>
          <el-table :data="paramOrPropData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.newParamVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addNewTag(scope.row)"
                  @blur="addNewTag(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  class="el-icon-edit"
                  @click="showEditParam(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数 -->
    <el-dialog
      :title="isParamOrProp"
      :visible.sync="paramDialogVisible"
      width="40%"
      @close="addParamColse"
    >
      <el-form
        label-width="100px"
        :model="addParamForm"
        ref="addParamFormRef"
        :rules="addParamFormRules"
      >
        <el-form-item :label="isParamOrProp" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paramDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加静态属性 -->
    <!-- <el-dialog title="静态属性" :visible.sync="propDialogVisible" width="40%" @close="addPropColse">
      <el-form label-width="100px" :model="addPropForm" ref="addPropFormRef" :rules="addPropFormRules">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="addPropForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="propDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProp">确 定</el-button>
      </span>
    </el-dialog>-->
    <!-- 编辑动态参数 -->
    <el-dialog
      :title="isParamOrProp"
      :visible.sync="editParamDialogVisible"
      width="40%"
      @close="editParamClose"
    >
      <el-form
        label-width="100px"
        :model="editParamForm"
        ref="editParamFormRef"
        :rules="editParamFormRules"
      >
        <el-form-item :label="isParamOrProp" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑静态属性 -->
    <!-- <el-dialog title="静态属性" :visible.sync="editPropDialogVisible" width="40%">
      <el-form label-width="100px" :model="editPropForm" ref="editPropFormRef" :rules="editPropFormRules">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="editPropForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editPropDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPropDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>-->
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      selectedKeys: [],
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeName: 'many',
      // 参数或属性表格数据
      paramOrPropData: [],
      // 参数或属性标签
      tagList: [],
      // 添加动态参数对话框的可见性
      paramDialogVisible: false,
      // propDialogVisible: false,
      editParamDialogVisible: false,
      // editPropDialogVisible: false,
      addParamFormRules: {
        attr_name: [
          { required: true, message: '输入不能为空！', trigger: 'blur' }
        ]
      },
      // addPropFormRules: {
      //   attr_name: [
      //     { required: true, message: '请输入动态参数！', trigger: 'blur'}
      //   ]
      // },
      editParamFormRules: {
        attr_name: [
          { required: true, message: '输入不能为空！', trigger: 'blur' }
        ]
      },
      // editPropFormRules: {
      //   attr_name: [
      //     { required: true, message: '请输入动态参数！', trigger: 'blur'}
      //   ]
      // },
      addParamForm: {
        attr_name: '',
        attr_sel: 'many',
        attr_vals: ''
      },
      // addPropForm: {
      //   attr_name: '',
      //   attr_sel: 'many',
      //   attr_vals:''
      // },
      editParamForm: {},
      // editPropForm: {}
      curId: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.cateList = res.data
    },
    cateChange() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.paramOrPropData = []
        return this.$message.warning('请选择三级分类！')
      }
      this.getParmOrProp()
    },
    async getParmOrProp() {
      const { data: res } = await this.$http.get(
        'categories/' +
          this.selectedKeys[this.selectedKeys.length - 1] +
          '/attributes',
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取失败！')
      res.data.forEach(item => {
        // if (item.attr_vals === '') return item.attr_vals = []
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.newParamVal = ''
      })
      this.paramOrPropData = res.data
      // this.tabList = this.paramOrPropData.attr_vals.split(',')
    },
    tabClick() {
      if (this.selectedKeys.length === 3) this.getParmOrProp()
    },
    // 添加动态参数
    showAddParam() {
      this.paramDialogVisible = true
    },
    async showEditParam(id) {
      this.curId = id
      this.editParamDialogVisible = true
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message('获取失败！')
      this.editParamForm = res.data
    },
    // showAddProp() {
    //   this.propDialogVisible = true
    // },
    addParam() {
      this.$refs.addParamFormRef.validate(async validate => {
        if (!validate) return this.$message('您输入的格式有误！')
        this.addParamForm.attr_sel = this.activeName
        const { data: res } = await this.$http.post(
          `categories/${this.selectedKeys[2]}/attributes`,
          this.addParamForm
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败！')
        this.paramDialogVisible = false
        this.getParmOrProp()
        this.$message.success('添加成功！')
      })
    },
    addParamColse() {
      this.$refs.addParamFormRef.resetFields()
      this.addParamForm = {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      }
    },
    editParam() {
      this.$refs.editParamFormRef.validate(async validate => {
        if (!validate) return this.$message('您输入的格式有误！')
        this.addParamForm.attr_sel = this.activeName
        const { data: res } = await this.$http.put(
          `categories/${this.selectedKeys[2]}/attributes/${this.curId}`,
          {
            attr_name: this.editParamForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editParamForm.attr_vals
          }
        )
        if (res.meta.status !== 200) return this.$message.error('更新失败！')
        this.editParamDialogVisible = false
        this.getParmOrProp()
        this.$message.success('更新成功！')
      })
    },
    editParamClose() {
      this.$refs.editParamFormRef.resetFields()
      this.addParamForm = {}
    },
    // addProp() {
    //   this.$refs.addPropFormRef.validate(async validate => {
    //     if (!validate) return this.$message('您输入的格式有误！')
    //     this.addPropForm.attr_sel = this.activeName
    //     const { data: res } = await this.$http.post(`categories/${this.selectedKeys[2]}/attributes`, this.addPropForm)
    //     if (res.meta.status !== 201) return this.$message.error('添加失败！')
    //     this.propDialogVisible = false
    //     this.getParmOrProp()
    //     this.$message.success('添加成功！')
    //   })
    // },
    // addPropColse() {
    //   this.$refs.addPropFormRef.resetFields()
    // },
    // 将后台相应的字符串分割成数组
    // tagArr(str) {
    //   if (str === '') return []
    //   return str.split(',')
    // },
    deleteParam(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.selectedKeys[2]}/attributes/${id}`
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败！')
          this.$message.success('删除成功！')
          this.getParmOrProp()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 回车或失去焦点时添加新可选参数
    addNewTag(row) {
      if (row.newParamVal.trim().length === 0) {
        row.newParamVal = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.newParamVal.trim())
      row.newParamVal = ''
      row.inputVisible = false
      this.setAttrVals(row)
    },
    async setAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.selectedKeys[2]}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败！')
      this.$message.success('修改参数项成功！')
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.setAttrVals(row)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    isBtnDisable() {
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    isParamOrProp() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-tabs {
  margin-top: 30px;
}
.el-tag {
  margin-right: 20px;
  margin-bottom: 10px;
}
body {
  margin: 0;
}
.input-new-tag {
  width: 120px;
}
</style>
